package com.example.demo.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.util.RedisUtil;
import com.example.demo.util.Result;
import com.example.demo.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author Cp
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-09-15 10:32:56
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<User> select() {
        return userMapper.selectList(null);
    }

    @Override
    public Result login(User user) {
        //数据库查询
        //先对密码加密,再查询
        user.setUserPassword(SecureUtil.md5(user.getUserPassword()));
        //编写查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("user_account", user.getUserAccount())
                .eq("user_password", user.getUserPassword());
        //查询
        User user1=userMapper.selectOne(queryWrapper);
        if(user1!=null){
            //数据库验证成功，创建token
            TokenUtil tokenUtil = new TokenUtil();
            String token = tokenUtil.createToken(user1);
            return new Result(200, "登录成功,返回token字符串", token);
        }
        return new Result(200, "登录失败,返回空", null);
    }

    @Override
    public Result register(User user) {
        //密码加密
        user.setUserPassword(SecureUtil.md5(user.getUserPassword()));
        //通过账号查询账号是否存在
        int num=userMapper.insert(user);

        return new Result(200, "注册成功", num);
    }

    @Override
    public Object add(User user) {
        user.setUserPassword(SecureUtil.md5(user.getUserPassword()));
        int num  =userMapper.insert(user);
        return new Result(200,"新增成功",num);
    }

    @Override
    public Result exit(String token) {
        redisUtil.delete(token);
        return new Result(200,"退出成功",null);
    }


}




